package com.hl.card.credit.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hl.card.credit.domain.*;
import com.hl.card.credit.mapper.CreditCardOrderMapper;
import com.hl.card.credit.service.CreditCardOrderService;
import com.hl.card.credit.service.RabbitMQService;
import com.hl.card.credit.service.remote.RemoteUserReslove;
import com.hl.card.credit.service.remote.RewardReslove;
import com.hl.card.credit.service.remote.UserReslove;
import com.hl.card.credit.utill.*;
import com.hl.card.credit.pub.model.PublicOrdersAllModel;

import java.util.*;

import com.hl.card.credit.service.PublicOrdersService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CreditCardOrderServiceImpl implements CreditCardOrderService {

    @Autowired
    private CreditCardOrderMapper creditCardOrderMapper;
    @Value("${checkToken}")
    private String urlString;

    @Autowired
    private UserReslove userReslove;

    @Autowired
    private RemoteUserReslove remoteUserReslove;


    @Autowired
    private PublicOrdersService publicOrdersService;

    @Autowired
    private RewardReslove rewardReslove;

    @Autowired
    private RabbitMQService rabbitMQService;

    @Autowired
    private CreditCardOrderService creditCardOrderService;

    /**
     * 创建订单
     *
     * @param orderVo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, timeout = 36000, rollbackFor = Exception.class)
    public void saveVo(CreditCardOrderVo orderVo) {
        /**
         * 查询是否有已有订单，如果有订单如何处理，如果没有如何处理(如果是无效订单删除？)
         *
         */
        PublicOrdersAllModel allModel = new PublicOrdersAllModel();
        allModel.setBusines_species("C");
        allModel.setBusiness_type("O");
        allModel.setPolicy_name(orderVo.getPolicyName());
        allModel.setCreate_date(new Date());
        allModel.setTelephone(orderVo.getPhone());
        allModel.setPhone_number(orderVo.getPhone());
        allModel.setOrder_time(new Date());
        allModel.setMerchant_code(orderVo.getMerchantCode());
        allModel.setStart_datetime(new Date());
        String order_code = CommonUtil.genOrderCode(allModel);
//        String order_code = publicOrdersService.addOrderCode(allModel);
        int num = publicOrdersService.addPublicOrders(allModel);
        CreditCardOrder order = new CreditCardOrder();
        BeanUtils.copyProperties(orderVo, order);
        order.setOrderCode(order_code);
        order.setPhone(order.getPhone());
        order.setBankType("平安银行");
//        order.setApplycompleted("P");
//        order.setApplicationstatus("D");
//        order.setMailed("D");
//        order.setActivated("D");
//        order.setFirstused("D");
        order.setCreatetime(new Date());
        order.setUpdatetime(new Date());
        order.setCurrentstatus("申请中");
        order.setStatus(0);//设置默认值
        RemoteUser remoteUser=remoteUserReslove.findSsoUserByUserId(orderVo.getUserid());
        if(null!=remoteUser){
            order.setUserName(remoteUser.getUserName());
            //设置用户名
        }
        /**
         * 奖励
         * 1.上级不存在
         *  》》申请人是群主
         *  》》不是群主
         *
         * 2.上级存在
         *  》》上级是群主
         *  》》上级不是群主
         *      》》》上级的上级存在
         *       》》》上级的上级不存在
         * 逻辑变更，如果用户有注册上级不走推荐关系
         *
         */
        User user3 = userReslove.getUserById(orderVo.getUserid());//当前申请用户,放开token验证，先不验证此用户是否存在
        User user2;
        User user1;
        String uid3 = orderVo.getUserid(), uid2 = null, uid1 = null;
        if (StringUtils.isNotEmpty(orderVo.getRegCode())) {//推荐申请
            String refer_code=user3.getRefer_reg_code();
            if(!StringUtils.isBlank(refer_code)){
                user2 = userReslove.getUserByRegCode(refer_code);//走注册关系
            }else{
                user2 = userReslove.getUserByRegCode(orderVo.getRegCode());//走推荐
            }
            if (user2.getIscommunityUser() != null && user2.getIscommunityUser().equals("1")) {//上级是群主,不再向上查找
                uid1 = uid2 = user2.getUserId();
            } else {
                uid2=user2.getUserId();
                String re_reg_code = user2.getRefer_reg_code();
                if (StringUtils.isNotEmpty(re_reg_code)) {
                    user1 = userReslove.getUserByRegCode(re_reg_code);//上级的上级
                    if(null!=user1){
                        uid1 = user1.getUserId();
                    }
                } else {
                    uid1 = null;
                }
            }
        } else {//主动申请
            if (user3.getIscommunityUser() != null && user3.getIscommunityUser().equals("1")) {//群主
                uid1 = uid2 = uid3;
            }
        }
        order.setParentUserid(uid2);
        order.setRootUserid(uid1);
        //查询用户是否新用户
        CreditCardOrderExample isNewEx=new CreditCardOrderExample();
        isNewEx.or().andStatusGreaterThan(1).andUseridEqualTo(order.getUserid());
        Long count= creditCardOrderMapper.countByExample(isNewEx);
        if(count>0){
            order.setIsnew(0);
        }else{
            order.setIsnew(1);
        }
        creditCardOrderMapper.insert(order);
    }
    /**
     * 创建订单
     *
     * @param order
     * @return
     */
    @Deprecated
//    @Override
    @Transactional(propagation = Propagation.REQUIRED, timeout = 36000, rollbackFor = Exception.class)
    public void save(CreditCardOrder order) {
        PublicOrdersAllModel allModel = new PublicOrdersAllModel();
        allModel.setBusines_species("C");
        allModel.setBusiness_type("C");
        allModel.setPolicy_name("C");
        allModel.setCreate_date(new Date());
        allModel.setTelephone(order.getPhone());
        allModel.setPhone_number(order.getPhone());
        allModel.setOrder_time(new Date());
        allModel.setMerchant_code(order.getMerchantCode());
        allModel.setStart_datetime(new Date());
        String order_code = CommonUtil.genOrderCode(allModel);
        allModel.setOrder_code(order_code);
        allModel.setCustomer_id(order.getUserid());
        order.setOrderCode(order_code);
        order.setPhone(order.getPhone());
        order.setBankType("平安银行");
        order.setApplycompleted("P");
        order.setApplicationstatus("D");
        order.setMailed("D");
        order.setActivated("D");
        order.setFirstused("D");
        order.setCreatetime(new Date());
        order.setUpdatetime(new Date());
        order.setCurrentstatus("申请中");
        creditCardOrderMapper.insert(order);
    }

    @Override
    public void update(CreditCardOrder user) {
        creditCardOrderMapper.updateByPrimaryKey(user);
    }

    @Override
    public CreditCardOrder findById(Long userId) {
        return creditCardOrderMapper.selectByPrimaryKey(userId);
    }

    @Override
    public CreditCardOrder findByOrderId(String orderId) {
        CreditCardOrderExample ex = new CreditCardOrderExample();
        ex.or().andOrderidEqualTo(orderId);
        List<CreditCardOrder> list = creditCardOrderMapper.selectByExample(ex);
        return list.isEmpty() ? null : list.get(0);
    }

    /**
     * 查询用户所有订单列表
     *
     * @param phone
     * @return
     */
    @Override
    public List<CreditCardOrder> list(String phone) {
        CreditCardOrderExample example = new CreditCardOrderExample();
        example.or().andPhoneEqualTo(phone);
        return creditCardOrderMapper.selectByExample(example);
    }

    @Override
    public PageInfo<CreditCardOrder> list(String phone, Integer start, Integer pageSize) {
        if (null != start && pageSize != null) {
            PageHelper.startPage(start, pageSize);
        }
        CreditCardOrderExample example = new CreditCardOrderExample();
        example.setOrderByClause("id desc");
        example.or().andPhoneEqualTo(phone);
        List cards = creditCardOrderMapper.selectByExample(example);
        PageInfo<CreditCardOrder> pageInfo = new PageInfo<CreditCardOrder>(cards);
        return pageInfo;
    }

    @Override
    public List<CreditCardOrder> findListByList(List<String> orderids) {
        CreditCardOrderExample ex = new CreditCardOrderExample();
        ex.or().andOrderCodeIn(orderids);
        List<CreditCardOrder> list = creditCardOrderMapper.selectByExample(ex);
        return list;
    }

    @Override
    public boolean checkToken(String token) {
        ResultUtil resultUtil = new ResultUtil();
        boolean flag = false;
        try {
            if (token != null && !token.isEmpty()) {
//                String urlString = "http://uc.bibitrip.com:808/checkToken";
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("token", token);
                String retStr = HttpUtil.post(urlString, paramMap);
                System.out.println(retStr);
                ResultUtil<TokenDtoResponse> tokenDtoResponse = JSON.parseObject(retStr, new TypeReference<ResultUtil<TokenDtoResponse>>() {
                });
                if (tokenDtoResponse.getStatus() == ExternalRetStatusUtil.S.getStatus()) {
                    if (tokenDtoResponse.getData().getCode() == 1) {
                        flag = true;
                    }
                    resultUtil.setData(tokenDtoResponse.getData().getCode());//0:未登录  1：已登陆
                    resultUtil.setMsg(ResultStatusUtil.Success.getName());
                    resultUtil.setStatus(ResultStatusUtil.Success.getStatus());
                } else {
                    resultUtil.setMsg("您未登录");
                }
            } else {
                resultUtil.setMsg("请传入token");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public CreditCardOrder getSatusByOrderCode(String orderCode) {
        //如果是无效订单删除？
        CreditCardOrderExample ex = new CreditCardOrderExample();
        ex.or().andOrderCodeEqualTo(orderCode);
        List<CreditCardOrder> list = creditCardOrderMapper.selectByExample(ex);

        if (list.isEmpty()) {
            return null;
        } else {
            return list.get(0);
        }
    }

    @Override
    public CreditCardOrder getSatusByOrderId(String orderId) {
        //如果是无效订单删除？
        CreditCardOrderExample ex = new CreditCardOrderExample();
        ex.or().andOrderidEqualTo(orderId);
        List<CreditCardOrder> list = creditCardOrderMapper.selectByExample(ex);
        if (list.isEmpty()) {
            return null;
        } else {
            return list.get(0);
        }
    }
    @Override
    public long countApplayOrder() {
        CreditCardOrderExample ex=new CreditCardOrderExample();
        ex.or().andStatusIsNotNull().andStatusNotEqualTo(0);
        long count=  creditCardOrderMapper.countByExample(ex);
        return count;
    }
    @Override
    public Map getRecommendApplayOrder(String userId) {
        CreditCardOrderExample ex3=new CreditCardOrderExample();
        ex3.or().andStatusIsNotNull().andStatusNotEqualTo(0).andParentUseridEqualTo(userId);
        List<CreditCardOrder> orders=creditCardOrderMapper.selectByExample(ex3);
        Map map=new HashMap();
        map.put("orders",orders);
        return map;
    }

    @Override
    public Map getRecommendApplayOrderPage(String userId, int pageNum, int pageSize) {
        CreditCardOrderExample ex3=new CreditCardOrderExample();
        ex3.or().andStatusIsNotNull().andStatusNotEqualTo(0).andParentUseridEqualTo(userId);
        PageHelper.startPage(pageNum, pageSize);
        List<CreditCardOrder> orders=creditCardOrderMapper.selectByExample(ex3);
        PageInfo<CreditCardOrder> pageInfo = new PageInfo<>(orders);
        DataGrid result = new DataGrid();
        result.setTotal(pageInfo.getTotal());
        if(pageNum<=pageInfo.getPages()){
            result.setRows(orders);
        }
        Map map=new HashMap();
        map.put("dataGrid",result);
        return map;
    }

    @Override
    public Map getRecommendApplayInfo(String userId) {
        CreditCardOrderExample ex=new CreditCardOrderExample();
        ex.or().andStatusIsNotNull().andStatusNotEqualTo(0).andParentUseridEqualTo(userId);
        long recommendCount=creditCardOrderMapper.countByExample(ex);
        CreditCardOrderExample ex2=new CreditCardOrderExample();
        List<Integer> list=new ArrayList<>();
        list.add(4);
        list.add(5);
        ex2.or().andStatusIn(list).andParentUseridEqualTo(userId);
        long activeCount=creditCardOrderMapper.countByExample(ex2);
        //累计未到账
        CreditCardOrderExample ex4=new CreditCardOrderExample();
        ex4.or().andStatusEqualTo(2).andParentUseridEqualTo(userId).andUseridNotEqualTo(userId);
        long profitOutcome=creditCardOrderMapper.sumProfitByExample(ex4);
        //累计已到账
        CreditCardOrderExample ex5=new CreditCardOrderExample();
        ex5.or().andStatusIn(list).andParentUseridEqualTo(userId).andUseridNotEqualTo(userId);;
        long profitIncome=creditCardOrderMapper.sumProfitByExample(ex5);
        Map map=new HashMap();
        map.put("recommendCount",recommendCount);
        map.put("activeCount",activeCount);
        map.put("profitIncome",profitIncome);
        map.put("profitOutcome",profitOutcome);
        return map;
    }
    @Override
    public List<CreditCardOrder> listAll(String condition) {
        CreditCardOrderExample ex=new CreditCardOrderExample();
        if(!StringUtils.isBlank(condition)){
            ex.or().andOrderidEqualTo(condition);
        }
        List<CreditCardOrder> list=creditCardOrderMapper.selectByExample(ex);
        return list;
    }
    @Override
    public Map listAll(int offset, int pageSize) {
        Map map=new HashMap();
        CreditCardOrderExample ex=new CreditCardOrderExample();
        PageHelper.startPage(offset, pageSize);
        List<CreditCardOrder> orders = creditCardOrderMapper.selectByExample(ex);
        PageInfo<CreditCardOrder> pageInfo = new PageInfo<>(orders);
        map.put("data",orders);
        map.put("total",pageInfo.getTotal());
        return map;
    }
    @Override
    public List<CreditCardOrder> findOrdersByUserId(String userId) {
        CreditCardOrderExample ex=new CreditCardOrderExample();
        ex.or().andUseridEqualTo(userId).andStatusGreaterThanOrEqualTo(0);
        List<CreditCardOrder> list=creditCardOrderMapper.selectByExample(ex);
        return list;
    }

    @Override
    public String reward(CreditCardOrder order) {
        Integer status=order.getStatus();
        Integer isNew=order.getIsnew();
        if(isNew.equals(1)&&status.equals(2)){//核卡发奖励
            ResponseObject responseObject= (ResponseObject) rewardReslove.commonReward("C",order.getOrderid(),order.getRootUserid()==null?"":order.getRootUserid(),order.getParentUserid()==null?"":order.getParentUserid(),order.getUserid(),"0","manual");
            System.out.println(JSON.toJSONString(responseObject));
            if(responseObject.getErroCode().equals(0)){
                JSONObject ro1= JSONObject.parseObject(responseObject.getData().toString());
                JSONObject ro2= JSONObject.parseObject(ro1.get("data").toString());
                String urs=String.valueOf(ro2.get("userId"));
                String uprs=String.valueOf(ro2.get("recommender"));
                String urrs=String.valueOf(ro2.get("communityAdmin"));
                String currency=String.valueOf(ro2.get("currency"));
                if(!urs.equals("null")){
                    order.setUseridReward(Integer.parseInt(urs));
                    if(!uprs.equals("null")){
                        order.setParentUseridReward(Integer.parseInt(uprs));
                    }
                    if(!urrs.equals("null")){
                        order.setRootUseridReward(Integer.parseInt(urrs));
                    }
                    if(!currency.equals("null")){
                        order.setCurrency(currency);
                    }
                }
            }
        }
        if(isNew.equals(1)&&status==4){//激活,消息通知解冻奖励
            //查询核卡奖励是否已发，未发放进行核卡奖励的发放
          if(StringUtils.isEmpty(order.getCurrency())){
              //核卡奖励补发
              ResponseObject responseObject= (ResponseObject) rewardReslove.commonReward("C",order.getOrderid(),order.getRootUserid()==null?"":order.getRootUserid(),order.getParentUserid()==null?"":order.getParentUserid(),order.getUserid(),"0","manual");
              System.out.println(JSON.toJSONString(responseObject));
              if(responseObject.getErroCode().equals(0)){
                  JSONObject ro1= JSONObject.parseObject(responseObject.getData().toString());
                  JSONObject ro2= JSONObject.parseObject(ro1.get("data").toString());
                  String urs=String.valueOf(ro2.get("userId"));
                  String uprs=String.valueOf(ro2.get("recommender"));
                  String urrs=String.valueOf(ro2.get("communityAdmin"));
                  String currency=String.valueOf(ro2.get("currency"));
                  if(!urs.equals("null")){
                      order.setUseridReward(Integer.parseInt(urs));
                      if(!uprs.equals("null")){
                          order.setParentUseridReward(Integer.parseInt(uprs));
                      }
                      if(!urrs.equals("null")){
                          order.setRootUseridReward(Integer.parseInt(urrs));
                      }
                      if(!currency.equals("null")){
                          order.setCurrency(currency);
                      }
                  }
              }
              creditCardOrderService.update(order);
          }
            Map<String, String> smap = new HashMap<String, String>();
            if(null!=order.getUserid()){
                smap.put("unfreeze", "manual");
                smap.put("userId", order.getUserid());
                smap.put("mchOrderNo", order.getOrderid());
                smap.put("amount", order.getUseridReward()==null?"0":order.getUseridReward().toString());
                smap.put("isFree", "isFree");
                rabbitMQService.send("queue.notify.mch.unfreeze",smap.toString());
            }
            if(null!=order.getParentUserid()){
                smap = new HashMap<String, String>();
                smap.put("unfreeze", "manual");
                smap.put("userId", order.getParentUserid());
                smap.put("mchOrderNo",order.getOrderid());
                smap.put("amount", order.getParentUseridReward()==null?"0":order.getParentUseridReward().toString());
                smap.put("isFree", "isFree");
                rabbitMQService.send("queue.notify.mch.unfreeze",smap.toString());
            }
            if(null!=order.getRootUserid()){
                smap = new HashMap<String, String>();
                smap.put("unfreeze", "manual");
                smap.put("userId", order.getRootUserid());
                smap.put("mchOrderNo", order.getOrderid());
                smap.put("amount",order.getRootUseridReward()==null?"0":order.getRootUseridReward().toString());
                smap.put("isFree", "isFree");
                rabbitMQService.send("queue.notify.mch.unfreeze",smap.toString());
            }
            System.out.println("信用卡激活奖励发放:" + order.getOrderid());
        }
        creditCardOrderService.update(order);
        return null;
    }
    @Override
    public String updateUserRelation(String userId, String parentId) {
        if(StringUtils.isBlank(parentId)){
            return null;
        }
        User user=userReslove.getUserById(userId);
        User parent=userReslove.getUserById(parentId);
        if(StringUtils.isBlank(user.getRefer_reg_code())){
            User param=new User();
            param.setUserId(userId);
            param.setRefer_reg_code(parent.getReg_code());
            userReslove.updatePartial(param);
        }
        return null;
    }
}
